<template>
  <picker
    class="xen-date-picker"
    :class="{ 'has-error': hasError, disabled: disabled }"
    mode="date"
    :value="modelValue"
    :start="startDate"
    :end="endDate"
    :disabled="disabled"
    @change="handleDateChange"
  >
    <view class="picker-content">
      <text
        class="picker-text"
        :class="{ 'has-value': modelValue, placeholder: !modelValue }"
      >
        {{ displayText }}
      </text>
      <uni-icons type="down" size="14" :color="disabled ? '#ccc' : '#999'" />
    </view>
  </picker>
</template>

<script setup lang="ts">
import { computed } from "vue";

// Props 定义
interface Props {
  modelValue?: string;
  placeholder?: string;
  startDate?: string;
  endDate?: string;
  disabled?: boolean;
  hasError?: boolean;
  format?: "YYYY-MM-DD" | "YYYY/MM/DD" | "MM/DD/YYYY";
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: "",
  placeholder: "请选择日期",
  startDate: "1900-01-01",
  endDate: "2100-12-31",
  disabled: false,
  hasError: false,
  format: "YYYY-MM-DD",
});

// Emits 定义
const emit = defineEmits<{
  "update:modelValue": [value: string];
  change: [value: string];
}>();

// 计算显示文本
const displayText = computed(() => {
  if (!props.modelValue) {
    return props.placeholder;
  }

  // 根据格式化要求处理日期显示
  if (props.format === "YYYY/MM/DD") {
    return props.modelValue.replace(/-/g, "/");
  } else if (props.format === "MM/DD/YYYY") {
    const parts = props.modelValue.split("-");
    if (parts.length === 3) {
      return `${parts[1]}/${parts[2]}/${parts[0]}`;
    }
  }

  return props.modelValue;
});

// 处理日期变化
const handleDateChange = (e: any) => {
  const value = e.detail.value;
  emit("update:modelValue", value);
  emit("change", value);
};
</script>

<style lang="scss" scoped>
.xen-date-picker {
  width: 100%;
  height: 44px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  background-color: #fff;
  line-height: 44px;
  box-sizing: border-box;
  transition: all 0.3s ease;

  &:active {
    border-color: #6366f1;
    box-shadow: 0 0 0 2px rgba(99, 102, 241, 0.1);
  }

  &.has-error {
    border-color: #ef4444;
    box-shadow: 0 0 0 2px rgba(239, 68, 68, 0.1);
  }

  &.disabled {
    background-color: #f5f5f5;
    border-color: #d9d9d9;
    cursor: not-allowed;
  }

  .picker-content {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 100%;
    padding: 0 12px;

    .picker-text {
      flex: 1;
      font-size: 14px;
      line-height: 1.5;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;

      &.has-value {
        color: #333;
        font-weight: 400;
      }

      &.placeholder {
        color: #999;
        font-weight: 300;
      }
    }
  }

  // 禁用状态下的文字颜色
  &.disabled .picker-content .picker-text {
    color: #ccc !important;
  }
}
</style>
